const cartModule = {
  namespaced: true,
  state: {
    cart: [],
  },
  getters: {
    cart: state => state.cart,
    // 购物车商品总数量
    total: state => state.cart.reduce((result, curr) => result + curr.amount, 0),
    // 商品全选
    allChecked: state => state.cart.every(prod => prod.checked),
    totalCheckedMoney: state => state.cart.reduce((result, curr) => curr.checked ? result + curr.price * curr.amount : result, 0),
  },
  mutations: {
    /**
     * 添加到购物车
     * @param {*} state
     * @param {*} payload 传递的是待加入购物车的商品对象 {id, title, image, price, amount}
     */
    addToCart(state, payload) {
      const has = state.cart.some(prod => prod.id === payload.id)
      if (has) {
        state.cart = state.cart.map(prod => {
          const copy = { ...prod }
          if (copy.id === payload.id) {
            copy.amount += payload.amount || 1
          }
          return copy
        })
      } else {
        state.cart.push({ ...payload, checked: true })
      }
    },
    removeFromCart(state, payload) {
      state.cart = state.cart.filter(prod => prod.id !== payload.id)
    },
    removeFromAllCecked(state) {
      state.cart = []
    },
    modifyAmount(state, payload) {
      state.cart = state.cart.map(prod => {
        const copy = { ...prod }
        if (copy.id === payload.id) {
          copy.amount = payload.amount
        }
        return copy
      })
    },
    modifyChecked(state, payload) {
      state.cart = state.cart.map(prod => {
        const copy = { ...prod }
        if (copy.id === payload.id) {
          copy.checked = !copy.checked
        }
        return copy
      })
    },
    modifyAllChecked(state, payload) {
      state.cart = state.cart.map(prod => {
        const copy = { ...prod }
        copy.checked = payload.checked
        return copy
      })
    },
  },
}
export default cartModule
